package com.trytech.mongoocrawler.common.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by coliza on 2018/5/24.
 */
public class MonitorData {
    private static MonitorData instance;
    //爬虫信息
    private ServerConfig serverConfig;
    //分布式模式下的客户端信息
    private List<ClientInfo> clientsConfig;

    private MonitorData() {
        serverConfig = new ServerConfig();
        clientsConfig = new ArrayList();
    }

    public static MonitorData getInstance() {
        if (instance == null) {
            instance = new MonitorData();
        }
        return instance;
    }

    public void registerClient(ClientInfo clientInfo) {
        updateCrawlerCount(serverConfig.getCrawlerCount() + 1);
        clientsConfig.add(clientInfo);
    }

    public void removeClient(final String clientIP) {
        if (serverConfig.getCrawlerCount() > 0) {
            updateCrawlerCount(serverConfig.getCrawlerCount() - 1);
        }
        clientsConfig = clientsConfig.stream().filter(clientInfo -> clientInfo.getIp().equals(clientIP)).collect(Collectors
                .toList());
    }

    public void updateMode(int mode) {
        serverConfig.setMode(mode);
    }

    public void updateModeLabel(String modeLabel) {
        serverConfig.setModeLabel(modeLabel);
    }

    public void updateCrawlerCount(int crawlerCount) {
        serverConfig.setCrawlerCount(crawlerCount);
    }

    public void updateRunStatus(String runStatus) {
        serverConfig.setRunStatusLabel(runStatus);
    }

    public ServerConfig getServerConfig() {
        if (serverConfig == null) {
            return new ServerConfig();
        }
        return serverConfig;
    }

    public void setServerConfig(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }

    public List<ClientInfo> getClientsConfig() {
        return clientsConfig;
    }
}
